package com.ygqh.baby.handler;

import com.ygqh.baby.ao.Message;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import com.ygqh.baby.model.WdtOrderImportExcelModel;
import com.ygqh.baby.po.YgWholesalerSku;
import com.ygqh.baby.service.YgWholesalerSkuService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author: sunshuo
 * @date: 2019/2/18 11:18
 */
@Component
public class WdtOrderExcelHandler {

	@Autowired
	private YgWholesalerSkuService ygWholesalerSkuService;

	/**
	 * @param excelInfo
	 * @return
	 */
	public Message handlerExcelInfo(Map<Integer, List<Row>> excelInfo) {
		List<WdtOrderImportExcelModel> detailList = new ArrayList<>(excelInfo.size());
		List<String> skuCodeList = new ArrayList<>();
		List<String> shopNameList = new ArrayList<>();
		DateFormat df3 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		for (Map.Entry<Integer, List<Row>> entry : excelInfo.entrySet()) {
			Integer sheet = entry.getKey();
			List<Row> rowList = entry.getValue();
			if (CollectionUtils.isEmpty(rowList)) {
				return Message.error("第" + (sheet + 1) + "个sheet的数据为空", null);
			}
			for (Row row : rowList) {
				WdtOrderImportExcelModel detail = new WdtOrderImportExcelModel();
				detail.setShopName(getCellValue(row.getCell(0), "", null));
				detail.setSourceOrderCode(getCellStringValue(row.getCell(1)));
				detail.setReceiver(getCellStringValue(row.getCell(2)));
				detail.setProvince(getCellStringValue(row.getCell(3)));
				detail.setCity(getCellStringValue(row.getCell(4)));
				detail.setArea(getCellStringValue(row.getCell(5)));
				detail.setTelPhone(getCellStringValue(row.getCell(6)));
				detail.setFixedLine(getCellStringValue(row.getCell(7)));
				detail.setZipCode(getCellStringValue(row.getCell(8)));
				detail.setUsername(getCellStringValue(row.getCell(9)));
				detail.setAddress(getCellStringValue(row.getCell(10)));
				detail.setSendType(getCellStringValue(row.getCell(11)));
				detail.setPostage(getCellBigDecimalValue(row.getCell(13)));
				detail.setDiscountedPrice(getCellBigDecimalValue(row.getCell(14)));
				detail.setCodBuyerFees(getCellBigDecimalValue(row.getCell(15)));
				detail.setOrderTime(getCellValue(row.getCell(16), null, df3));
				detail.setPayTime(getCellValue(row.getCell(17), null, df3));
				detail.setBuyerRemark(getCellStringValue(row.getCell(18)));
				detail.setCustomerRemark(getCellStringValue(row.getCell(19)));
				detail.setInvoiceTitle(getCellStringValue(row.getCell(20)));
				detail.setInvoiceContent(getCellStringValue(row.getCell(21)));
				detail.setPayType(getCellStringValue(row.getCell(22)));
				detail.setSkuCode(getCellStringValue(row.getCell(23)));
				detail.setGoodsQuantity(getCellLongValue(row.getCell(24)));
				detail.setGoodsDiscountedPrice(getCellBigDecimalValue(row.getCell(27)));
				detail.setSourceSubOrderCode(getCellStringValue(row.getCell(28)));
				detail.setRemark(getCellStringValue(row.getCell(29)));

				detail.validateParam();

				if (StringUtils.isNotBlank(detail.getErrMsg())) {
					return Message.error("第" + sheet + "个sheet, 第" + row.getRowNum() + "行的数据异常：" + detail.getErrMsg(), null);
				}

				if (StringUtils.isNotBlank(detail.getShopName()) && !shopNameList.contains(detail.getShopName())) {
					shopNameList.add(detail.getShopName());
				}
				if (StringUtils.isNotBlank(detail.getSkuCode()) && !skuCodeList.contains(detail.getSkuCode())) {
					skuCodeList.add(detail.getSkuCode());
				}
				detailList.add(detail);
			}
		}
		Message message = setOrderPrice(detailList, skuCodeList, shopNameList);
		if (Message.isSuccess(message)) {
			message.setExtra(detailList);
		}
		return message;
	}

	/**
	 * 设置订单价格
	 * @param detailList
	 * @param skuCodeList
	 * @param shopNameList
	 * @return
	 */
	private Message setOrderPrice(List<WdtOrderImportExcelModel> detailList, List<String> skuCodeList, List<String> shopNameList) {
		Message message = setDetailPrice(detailList, skuCodeList, shopNameList);
		if (!Message.isSuccess(message)) {
			return message;
		}
		Map<String, List<WdtOrderImportExcelModel>> collect = detailList.stream()
				.collect(Collectors.groupingBy(WdtOrderImportExcelModel::getSourceOrderCode));
		collect.forEach((sourceOrderCode, list) -> {
			BigDecimal totalGoodsPrice = list.stream().map(WdtOrderImportExcelModel::getGoodsTotalPrice).reduce(BigDecimal::add).get();
			BigDecimal postage = list.get(0).getPostage();
			if (postage != null) {
				totalGoodsPrice = totalGoodsPrice.add(postage);
			}
			BigDecimal totalReceivable = totalGoodsPrice;
			list.forEach(o -> o.setTotalReceivable(totalReceivable));
		});
		return Message.success(null);
	}

	/**
	 * 设置订单明细价格
	 * @param detailList
	 * @param skuCodeList
	 * @param shopNameList
	 * @return
	 */
	private Message setDetailPrice(List<WdtOrderImportExcelModel> detailList, List<String> skuCodeList, List<String> shopNameList) {
		List<YgWholesalerSku> skuList = ygWholesalerSkuService.findBySkuCodeAndWholesaleName(skuCodeList, shopNameList);
		Map<String, List<YgWholesalerSku>> skuGroupByWholesalerName = skuList.stream()
				.collect(Collectors.groupingBy(YgWholesalerSku::getWholesalerName));
		Map<String, List<WdtOrderImportExcelModel>> excelInfoGroupByShopName = detailList.stream()
				.collect(Collectors.groupingBy(WdtOrderImportExcelModel::getShopName));
		for (Map.Entry<String, List<WdtOrderImportExcelModel>> entry : excelInfoGroupByShopName.entrySet()) {
			String shopName = entry.getKey();
			if (StringUtils.isBlank(shopName)) {
				continue;
			}
			List<WdtOrderImportExcelModel> infoList = entry.getValue();
			if (!skuGroupByWholesalerName.containsKey(shopName)) {
				infoList.forEach(info -> info.addErrMsg("店铺名称不存在或尚未设置店铺批发价；"));
				return Message.error("店铺名称[" + shopName + "]不存在或尚未设置店铺批发价", null);
			} else {
				Map<String, List<YgWholesalerSku>> skuGroupBySkuCode = skuGroupByWholesalerName.get(shopName).stream()
						.collect(Collectors.groupingBy(YgWholesalerSku::getSkuCode));
				for (WdtOrderImportExcelModel info : infoList) {
					if (StringUtils.isBlank(info.getSkuCode())) {
						continue;
					}
					if (!skuGroupBySkuCode.containsKey(info.getSkuCode())) {
						info.addErrMsg("商家编码批发价未设置；");
						return Message.error("店铺名称[" + shopName + "],SKU[" + info.getSkuCode() + "]尚未设置批发价", null);
					} else {
						BigDecimal wholesalePrice = skuGroupBySkuCode.get(info.getSkuCode()).get(0).getWholesalePrice();
						info.setGoodsPrice(wholesalePrice);
						if (info.getGoodsQuantity() != null) {
							info.setGoodsTotalPrice(wholesalePrice.multiply(BigDecimal.valueOf(info.getGoodsQuantity())));
						}
					}
				}
			}
		}
		return Message.success(null);
	}

	private boolean isCellDate(Cell cell) {
		try {
			return HSSFDateUtil.isCellDateFormatted(cell);
		} catch (Exception e) {
			return false;
		}
	}

	private BigDecimal getCellBigDecimalValue(Cell hssfCell) {
		String cellValue = getCellValue(hssfCell, null, new DecimalFormat("0.00"));
		if (StringUtils.isBlank(cellValue)) {
			return null;
		}
		return new BigDecimal(cellValue);
	}

	private Long getCellLongValue(Cell hssfCell) {
		String cellValue = getCellValue(hssfCell, null, new DecimalFormat("0"));
		if (StringUtils.isBlank(cellValue)) {
			return null;
		}
		return Long.valueOf(cellValue);
	}

	private String getCellStringValue(Cell hssfCell) {
		return getCellValue(hssfCell, null, null);
	}

	private String getCellValue(Cell hssfCell, String defaultValue, Format format) {
		if (hssfCell == null) {
			return defaultValue;
		}
		if (hssfCell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
			// 返回布尔类型的值
			return String.valueOf(hssfCell.getBooleanCellValue());
		} else if (isCellDate(hssfCell)) {
			// 返回日期类型的值
			if (format == null) {
				format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			}
			return format.format(hssfCell.getDateCellValue());
		} else if (hssfCell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
			// 返回数值类型的值
			if (format == null) {
				format = new DecimalFormat("0");
			}
			return format.format(hssfCell.getNumericCellValue());
		} else {
			// 返回字符串类型的值
			return String.valueOf(hssfCell.getStringCellValue()).trim();
		}
	}

}
